package com.inwavetech.os;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.ContentResolver;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.inwavetech.os.util.DaoHelper;
import com.inwavetech.os.util.Form;
import com.inwavetech.os.util.LoaderAnimation;
import com.inwavetech.os.util.SessionManager;
import com.inwavetech.os.util.SimpleResponse;
import com.inwavetech.os.util.SyncUtils;
import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;

import java.util.HashMap;


/*
private static final long SYNC_INTERVAL = 30L * 60L; // 30 mins

String contentAuthority = context.getString(R.string.geocapture_content_authority);

// configure account as syncable
ContentResolver.setIsSyncable(account, contentAuthority, 1);
// configure the account to sync automatically
ContentResolver.setSyncAutomatically(account, contentAuthority, true);
// configure the sync interval
ContentResolver.addPeriodicSync(account, contentAuthority, new Bundle(), SYNC_INTERVAL);

// Disable sync backoff and ignore sync preferences. In other words...perform sync NOW!
Bundle bundle = new Bundle();
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
ContentResolver.requestSync(
        account,
        contentAuthority,
        bundle);


contentResolver = getContentResolver();

// register the send finished os sync
ContentResolver.addPeriodicSync(account, AUTHORITY, new Bundle(), SYNC_INTERVAL);

Bundle bundle = new Bundle();
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_FORCE, true);
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
ContentResolver.requestSync(null, MyContentProvider.getAuthority(), bundle);
*/
public class LoginActivity extends OrmLiteBaseActivity<DaoHelper> {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        final SessionManager sessionManager = new SessionManager(this, getHelper());

        final HashMap<String, EditText> formFields = new HashMap<String, EditText>();
        formFields.put("username", (EditText) findViewById(R.id.username));
        formFields.put("password", (EditText) findViewById(R.id.password));

        Button submit = (Button) findViewById(R.id.submit);

        Form.UrlBuilderInterface urlBuilder = new Form.UrlBuilderInterface() {
            @Override
            public String build() {
                return getString(R.string.api_get_token_url);
            }
        };

        Form.ResponseHandlerInterface responseHandler = new Form.ResponseHandlerInterface() {

            @Override
            public void handle(SimpleResponse response) {
                if (response != null) {
                    switch (response.code) {

                        case 200:
                            new SyncUtils(getApplicationContext()).registerSync();

                            String username = formFields.get("username").getText().toString();
                            String token = response.body;

                            try {
                                sessionManager.createLoginSession(username, token);
                                Intent i = new Intent(getApplicationContext(), MainActivity.class);
                                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                                startActivity(i);
                                finish();
                            } catch (SessionManager.SessionManagerException e) {
                                Toast.makeText(getApplicationContext(), getString(R.string.login_fail), Toast.LENGTH_LONG).show();
                            }

                            break;

                        case 401:
                            Toast.makeText(getApplicationContext(), getString(R.string.message_auth_bad_credentials), Toast.LENGTH_LONG).show();

                            break;

                        default:
                            apiErrorMessage();

                            break;

                    }
                } else {
                    apiErrorMessage();
                }
            }

        };

        LoaderAnimation loaderAnimation = new LoaderAnimation(getLayoutInflater(), (ViewGroup) findViewById(R.id.container));

        Form form = new Form(this, loaderAnimation, formFields, submit, urlBuilder, responseHandler);
    }

    private void apiErrorMessage() {
        Log.e(LoginActivity.class.getName(), getString(R.string.unknown_server_response));
        Toast.makeText(this, getString(R.string.message_api_error), Toast.LENGTH_LONG).show();
    }


}
